import React, { useState, useEffect } from 'react';
import { Button, Descriptions, Input, message, Spin, Select, Upload } from 'antd';
import { AddSupplier, GetBusinessTypes } from '../../api/supplier';
import { useNavigate } from 'react-router-dom';
const { TextArea } = Input;

const Addsupplier = () => {

    const navigate = useNavigate();
    const [spinning, setSpinning] = React.useState(false);//加载中
    const [name, setName] = useState('');
    const [phone, setPhone] = useState('');
    const [isButtonDisabled, setIsButtonDisabled] = useState(true); // 初始时禁用按钮 
    const [enterpriseName,setEnterpriseName]=useState('');
    const [address,setAddress]=useState('');
    const [announcement,setAnnouncement]=useState('');
    const [jydata, setjyData] = useState([]);
    const add = async () => {
        setSpinning(true);
        await AddSupplier({
            enterpriseName:enterpriseName,
            phone: phone,
            name: name,
            type:type,
            address:address,
            announcement:announcement,
            logo:logoUrl,
            photo:imageUrl,
            qualification:qualification,
            types:jydata
        }).then((res) => {
            if (res.result === 0) {
                setSpinning(false);
                message.success('添加成功', 1.5);
                navigate(`/supplier`);
            }
        })

    }
    const [type, setType] = useState('');
   
    const data = async () => {
        await GetBusinessTypes({
        }).then((res) => {
            if (res.result === 0) {
                setjyData(res.data.data);
            }
        })
    }
    useEffect(() => {
        data();
    }, []); // 空数组意味着这个effect只在组件挂载和卸载时运行  

    const options = jydata.map((item) => ({
        value: item.id,
        label: item.name,
    }));
   
    const [logoUrl, setlogoUrll] = useState();
    const [imageUrl, setImageUrl] = useState();
    const [qualification, setQualification] = useState();
    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj, (url) => {
                setlogoUrll(info.fileList[0].response);
            });
        }
    };
    const handleChanges = (info) => {
        if (info.file.status === 'uploading') {
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj, (url) => {
                
                setImageUrl(info.fileList[0].response);
               
            });
        }
    };
    const handleChangess = (info) => {
        if (info.file.status === 'uploading') {
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj, (url) => {
                setQualification(info.fileList[0].response);     
            });
        }
    };
    const getBase64 = (img, callback) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    };
    const beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('您只能上传JPG/PNG文件!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('图像必须小于2MB!');
        }
        return isJpgOrPng && isLt2M;
    };
    const handleNameChange = (e) => {
        setName(e.target.value);
    };
   const handleEnterpriseNameChange=(e)=>{
        setEnterpriseName(e.target.value)
   }
    const handleChangeType = (value) => {
        setType(value);
        console.log( setType(value))
    };
    const handlePhoneChange = (e) => {
        const value = e.target.value;
        setPhone(value);
        setIsButtonDisabled(value.length !== 11);
    };
    const handleAddressChangeType = (e) => {
        setAddress(e.target.value)
    };
  const handleAnnouncementChangeType=(e)=>{
    setAnnouncement(e.target.value)
  }


    const items = [
        {
            key: '1',
            label: '名称',
            children: <Input placeholder="请输入名称" onChange={handleEnterpriseNameChange} value={enterpriseName} />,
        },
        {
            key: '2',
            label: '电话',
            children: <Input placeholder="请输入电话号码" maxLength={11} onChange={handlePhoneChange} onBlur={handlePhoneChange} value={phone} />,
            span: 2,
        },
        {
            key: '3',
            label: '负责人',
            children: <Input onChange={handleNameChange} value={name} />,
        },
        {
            key: '4',
            label: '经营总类',
            children: <>
                <Select defaultValue={jydata}
                    style={{ width: "100%" }}
                    placeholder="选择经营总类"
                    onChange={handleChangeType}
                    options={options} />   </>,
            span: 2,
        },
        {
            key: '5',
            label: '地址',
            children: <TextArea rows={3} maxLength={6} onChange={handleAddressChangeType} value={address} />,
        },
        {
            key: '6',
            label: '企业公告',
            children: <TextArea rows={3} maxLength={6} onChange={handleAnnouncementChangeType} value={announcement}/>,
            span: 2,
        },
        {
            key: '7',
            label: '企业logo',
            children: <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="https://sapi.jiangdaye.cn/api/Resource/Upload"
                beforeUpload={beforeUpload}
                onChange={handleChange}>
                {logoUrl ? (
                    <img src={logoUrl} alt="avatar" style={{ width: '100%'}}/>) : ('点击选择图片')}
            </Upload>,
            span: 2,
        },
        {
            key: '8',
            label: '企业图片',
            children: <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="https://sapi.jiangdaye.cn/api/Resource/Upload"
                beforeUpload={beforeUpload}
                onChange={handleChanges}>
                {imageUrl ? (
                    <img src={imageUrl} alt="avatar"style={{ width: '100%' }}/> ) : ( '点击选择图片' )}
            </Upload>,
            span: 2,
        },
        {
            key: '9',
            label: '企业资质文件',
            children: <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="https://sapi.jiangdaye.cn/api/Resource/Upload"
                beforeUpload={beforeUpload}
                onChange={handleChangess} >
                {qualification ? (
                     <img src={qualification} alt="qualificationav" style={{width: '100%' }}/> ) : ( '点击选择图片' )}
            </Upload>,
            span: 3,
        },

        {
            key: '10',
            label: '行为',
            children: <Button type="primary" onClick={() => add()} disabled={isButtonDisabled} x>新增</Button>,
            span: 3,
        },

    ];
    return (
        <div className='exam-container'>
            <div className="container">
                <div className="content">
                    <Descriptions title="新增供应商" layout="vertical" bordered items={items} />
                    <Spin spinning={spinning} tip="Loading" fullscreen />
                </div></div></div>
    );
};
export default Addsupplier;